<template>
  <div class="app-container">
    <!-- 引入计划选择器组件 -->
    <PlanSelector 
      ref="planSelectorRef" 
      v-model:visible="planSelectorVisible" 
      @select="handlePlanSelected" 
    />
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="工单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <!-- <el-form-item label="关联计划" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入关联计划名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
            <el-form-item label="关联计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择关联计划"
          clearable
          @keyup.enter="handleQuery"
        >
        <el-option
          v-for="item in planOptions"
          :key="item.planId"
          :label="item.planName"
          :value="item.planId"
        />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品"
          clearable
          @keyup.enter="handleQuery"
        >
        <el-option
          v-for="item in productOptions"
          :key="item.productId"
          :label="item.productName"
          :value="item.productId"
        />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="生产线ID" prop="lineId">
        <el-input
          v-model="queryParams.lineId"
          placeholder="请输入生产线ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="生产线" prop="lineId">
          <el-select
            v-model="queryParams.lineId"
            placeholder="请选择生产线"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in lineOptions"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="计划生产数量" prop="planQuantity">
        <el-input
          v-model="queryParams.planQuantity"
          placeholder="请输入计划生产数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成数量" prop="finishedQuantity">
        <el-input
          v-model="queryParams.finishedQuantity"
          placeholder="请输入完成数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="不良品数量" prop="defectQuantity">
        <el-input
          v-model="queryParams.defectQuantity"
          placeholder="请输入不良品数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择工单状态" clearable>
          <el-option
            v-for="dict in work_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:workorder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:workorder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:workorder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pm:workorder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workorderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单ID" align="center" prop="orderId" />
      <el-table-column label="工单编号" align="center" prop="orderCode" />
      <el-table-column label="关联计划" align="center" prop="planName" />
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="生产线" align="center" prop="lineName" />
      <el-table-column label="计划生产数量" align="center" prop="planQuantity" />
      <el-table-column label="完成数量" align="center" prop="finishedQuantity" />
      <el-table-column label="不良品数量" align="center" prop="defectQuantity" />
      <el-table-column label="工单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="work_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pm:workorder:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pm:workorder:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="workorderRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编号" prop="orderCode">
              <el-input v-model="form.orderCode" placeholder="请输入工单编号" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="关联计划" prop="planId">
              <div class="plan-selector-container">
                <el-input 
                  v-model="selectedPlanName" 
                  placeholder="请选择关联计划" 
                  readonly 
                  class="plan-input"
                  disabled
                >
                  <template #append>
                    <el-button @click="openPlanSelector">选择</el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select 
                v-model="form.productId" 
                placeholder="请选择产品" 
                disabled 
                style="width: 100%"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="生产线" prop="lineId">
              <el-select 
                v-model="form.lineId" 
                placeholder="请选择生产线" 
                disabled 
                style="width: 100%"
              >
                <el-option
                  v-for="item in lineOptions"
                  :key="item.lineId"
                  :label="item.lineName"
                  :value="item.lineId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="计划生产数量" prop="planQuantity">
              <el-input v-model="form.planQuantity" placeholder="请输入计划生产数量" disabled/>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="完成数量" prop="finishedQuantity">
              <el-input v-model="form.finishedQuantity" placeholder="请输入完成数量" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="不良品数量" prop="defectQuantity">
              <el-input v-model="form.defectQuantity" placeholder="请输入不良品数量" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="工单状态" prop="status">
              <el-select 
                v-model="form.status" 
                placeholder="请选择工单状态" 
                style="width: 100%"
              >
                <el-option
                  v-for="dict in work_order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Workorder">
import { listWorkorder, getWorkorder, delWorkorder, addWorkorder, updateWorkorder, listProduct, listLine ,listPlan, } from "@/api/pm/workorder";
import { getPlan , updatePlan} from "@/api/pm/plan";
import PlanSelector from "@/components/PlanSelector/index.vue";
import { generateWorkorderCode } from "@/utils/generator";
const { proxy } = getCurrentInstance();
const { work_order_status, plan_status } = proxy.useDict('work_order_status', 'plan_status');

const workorderList = ref([]);
const productOptions = ref([]); // 产品下拉框选项
const lineOptions = ref([]); // 生产线下拉框选项
const planOptions = ref([]);   // 关联计划下拉框选项
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeStartTime = ref([]);
const daterangeEndTime = ref([]);
const planSelectorVisible = ref(false);
const planSelectorRef = ref(null);
const selectedPlanName = ref('');
const originalPlanId = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderCode: null,
    planId: null,
    planName: null,
    productId: null,
    lineId: null,
    planQuantity: null,
    finishedQuantity: null,
    defectQuantity: null,
    status: null,
  },
  rules: {
    orderCode: [
      { required: true, message: "工单编号不能为空", trigger: "blur" }
    ],
    planId: [
      { required: true, message: "关联计划不能为空", trigger: "change" }
    ],
    productId: [
      { required: true, message: "产品不能为空", trigger: "change" }
    ],
    lineId: [
      { required: true, message: "生产线不能为空", trigger: "change" }
    ],
    planQuantity: [
      { required: true, message: "计划生产数量不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询生产工单列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeStartTime && '' != daterangeStartTime) {
    queryParams.value.params["beginStartTime"] = daterangeStartTime.value[0];
    queryParams.value.params["endStartTime"] = daterangeStartTime.value[1];
  }
  if (null != daterangeEndTime && '' != daterangeEndTime) {
    queryParams.value.params["beginEndTime"] = daterangeEndTime.value[0];
    queryParams.value.params["endEndTime"] = daterangeEndTime.value[1];
  }
  listWorkorder(queryParams.value).then(response => {
    workorderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderCode: null,
    planId: null,
    planName: null,
    productId: null,
    lineId: null,
    planQuantity: null,
    finishedQuantity: null,
    defectQuantity: null,
    startTime: null,
    endTime: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  selectedPlanName.value = '';
  originalPlanId.value = null;
  proxy.resetForm("workorderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeStartTime.value = [];
  daterangeEndTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.orderCode = generateWorkorderCode();
  title.value = "添加生产工单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value
  getWorkorder(_orderId).then(response => {
    form.value = response.data;
    // 保存原始关联计划ID，用于后续判断计划是否变更
    originalPlanId.value = form.value.planId;
    
    // 如果有关联计划ID，设置计划名称
    if (form.value.planId) {
      selectedPlanName.value = form.value.planName || '';
    }
    open.value = true;
    title.value = "修改生产工单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workorderRef"].validate(valid => {
    if (valid) {
      // 确保表单中包含计划名称
      if (form.value.planId && selectedPlanName.value) {
        form.value.planName = selectedPlanName.value;
      }
      
      // 保存工单
      const saveWorkorder = form.value.orderId != null 
        ? updateWorkorder(form.value) 
        : addWorkorder(form.value);
        
      saveWorkorder.then(response => {
        // 处理计划状态更新
        
        // 情况1: 新增工单
        if (!form.value.orderId && form.value.planId) {
          updatePlanStatus(form.value.planId, '1'); // 将新计划设为"进行中"(1)
        } 
        // 情况2: 修改工单且计划ID发生变化
        else if (form.value.orderId && form.value.planId !== originalPlanId.value) {
          // 如果原计划ID存在，先将原计划状态重置为"未开始"
          if (originalPlanId.value) {
            updatePlanStatus(originalPlanId.value, '0'); // 将原计划设为"未开始"(0)
          }
          // 将新计划状态设置为"进行中"
          if (form.value.planId) {
            updatePlanStatus(form.value.planId, '1'); // 将新计划设为"进行中"(1)
          }
        }
        proxy.$modal.msgSuccess(form.value.orderId != null ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

// 更新计划状态的通用函数
function updatePlanStatus(planId, statusCode) {
  if (!planId) return;
  
  // 先获取计划当前信息
  getPlan(planId).then(planRes => {
    if (planRes.data) {
      const planData = planRes.data;
      if (statusCode === '1' && planData.status === '2') {
        console.log(`计划[${planId}]已完成，不更新状态`);
        return;
      }
      // 设置为"未开始"状态时，不更新已完成或有其他工单关联的计划
      if (statusCode === '0') {
        if (planData.status === '2') {
          console.log(`计划[${planId}]已完成，不更新状态`);
          return;
        }
      }
      
      // 更新计划状态
      updatePlan({
        planId: planId,
        status: statusCode
      }).then(() => {
        console.log(`计划[${planId}]状态已更新为${statusCode === '0' ? '未开始' : '进行中'}`);
      }).catch(err => {
        console.error(`更新计划[${planId}]状态失败:`, err);
      });
    }
  }).catch(err => {
    console.error(`获取计划[${planId}]信息失败:`, err);
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal.confirm('是否确认删除生产工单编号为"' + _orderIds + '"的数据项？').then(function() {
    return delWorkorder(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pm/workorder/export', {
    ...queryParams.value
  }, `workorder_${new Date().getTime()}.xlsx`)
}

// 在组件挂载时获取数据
onMounted(() => {
  // 获取产品（不分页）列表
  listProduct().then(response => {
    productOptions.value = response.data; // 根据你的接口返回结构调整
  });
  // 获取生产线（不分页）列表
  listLine().then(response => {
    lineOptions.value = response.data; // 根据你的接口返回结构调整
  });
  // 获取关联计划（不分页）列表
  listPlan().then(response => {
    planOptions.value = response.data; // 根据你的接口返回结构调整
  });
  getList(); // 原有的获取计划列表
});

// 打开计划选择器
function openPlanSelector() {
  planSelectorRef.value.open();
  planSelectorVisible.value = true;
}

// 处理计划选择事件
function handlePlanSelected(plan) {
  if (plan) {
    form.value.planId = plan.planId;
    selectedPlanName.value = plan.planName;
    
    // 自动填充产品和生产线信息
    if (plan.productId) {
      form.value.productId = plan.productId;
      // 查找产品名称
      const product = productOptions.value.find(p => p.productId === plan.productId);
      if (product) {
        form.value.productName = product.productName;
      }
    }
    
    if (plan.lineId) {
      form.value.lineId = plan.lineId;
      // 查找生产线名称
      const line = lineOptions.value.find(l => l.lineId === plan.lineId);
      if (line) {
        form.value.lineName = line.lineName;
      }
    }
    
    if (plan.planQuantity) {
      form.value.planQuantity = plan.planQuantity;
    }
    
    // 如果是新增工单，自动填充工单编号 (WO + 计划编号)
    if (!form.value.orderId && !form.value.orderCode && plan.planCode) {
      form.value.orderCode = 'WO' + plan.planCode;
    }
    
    // 默认工单状态为待分配
    if (!form.value.status) {
      form.value.status = '0'; // 待分配状态
    }
    
    // 将计划名称也保存到表单中
    form.value.planName = plan.planName;
  }
}

// 新增查看计划详情的方法
function viewPlanDetail(planId) {
  if (!planId) return;
  
  getPlan(planId).then(response => {
    if (response.data) {
      // 显示计划详情
      proxy.$modal.open({
        title: '计划详情',
        content: `
          <div>
            <p><strong>计划编号：</strong>${response.data.planCode || '-'}</p>
            <p><strong>计划名称：</strong>${response.data.planName || '-'}</p>
            <p><strong>产品：</strong>${response.data.productName || '-'}</p>
            <p><strong>生产线：</strong>${response.data.lineName || '-'}</p>
            <p><strong>计划数量：</strong>${response.data.planQuantity || '-'}</p>
            <p><strong>计划状态：</strong>${getDictLabel(plan_status, response.data.status) || '-'}</p>
          </div>
        `,
        btn: ['关闭'],
        callback: (action, instance) => {
          instance.close();
        }
      });
    }
  });
}

// 获取字典标签的辅助函数
function getDictLabel(dict, value) {
  if (!dict || !value) return '';
  const item = dict.find(d => d.value === value);
  return item ? item.label : '';
}
</script>

<style scoped>
.plan-selector-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.plan-input {
  width: 100%;
  max-width: 300px;
}
.plan-tag {
  margin-top: 5px;
  margin-left: 5px;
}
</style>
